/**
 * 点名管理模块
 * 负责点名功能和点名记录的管理
 */

// 点名管理类
class AttendanceManager {
    constructor() {
        this.attendanceRecords = [];
        this.currentDate = this.formatDate(new Date());
        this.todayAttendance = [];
        this.randomStudent = null;
        this.loadAttendanceRecords();
        this.initEventListeners();
    }

    // 从localStorage加载点名记录
    loadAttendanceRecords() {
        const storedRecords = localStorage.getItem('attendanceRecords');
        this.attendanceRecords = storedRecords ? JSON.parse(storedRecords) : [];
        this.filterTodayAttendance();
    }

    // 保存点名记录到localStorage
    saveAttendanceRecords() {
        localStorage.setItem('attendanceRecords', JSON.stringify(this.attendanceRecords));
    }

    // 过滤今日点名记录
    filterTodayAttendance() {
        this.todayAttendance = this.attendanceRecords.filter(record =>
            record.date === this.currentDate
        );
    }

    // 格式化日期为YYYY-MM-DD
    formatDate(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }

    // 添加点名记录
    addAttendanceRecord(studentId, status) {
        // 检查学生是否存在
        const student = studentManager.getStudentById(studentId);
        if (!student) {
            return false;
        }

        // 检查今天是否已经点过名
        const existingRecord = this.todayAttendance.find(record => record.studentId === studentId);

        if (existingRecord) {
            // 更新现有记录
            existingRecord.status = status;
            existingRecord.timestamp = new Date().toISOString();
        } else {
            // 创建新记录
            const newRecord = {
                studentId,
                studentName: student.name,
                date: this.currentDate,
                timestamp: new Date().toISOString(),
                status
            };

            this.attendanceRecords.push(newRecord);
            this.todayAttendance.push(newRecord);
        }

        this.saveAttendanceRecords();
        // 更新统计信息
        this.renderAttendanceStatistics();
        return true;
    }

    // 获取点名状态显示文本
    getStatusText(status) {
        switch (status) {
            case 'present': return '出勤';
            case 'late': return '迟到';
            case 'absent': return '旷课';
            case 'early-leave': return '早退';
            default: return '未知';
        }
    }

    // 获取点名状态CSS类
    getStatusClass(status) {
        switch (status) {
            case 'present': return 'status-present';
            case 'late': return 'status-late';
            case 'absent': return 'status-absent';
            case 'early-leave': return 'status-early-leave';
            default: return '';
        }
    }

    // 全部点名
    attendAll() {
        const students = studentManager.getAllStudents();

        if (students.length === 0) {
            alert('没有学生信息，请先添加学生');
            return;
        }

        // 重置今日点名记录
        this.todayAttendance = [];

        // 为每个学生创建默认为"出勤"的记录
        students.forEach(student => {
            this.addAttendanceRecord(student.id, 'present');
        });

        this.renderAttendanceList();
        this.showMessage('success', '全部点名完成，默认状态为"出勤"');
    }

    // 随机点名
    randomAttendance() {
        const students = studentManager.getAllStudents();

        if (students.length === 0) {
            alert('没有学生信息，请先添加学生');
            return;
        }

        // 随机选择一个学生
        const randomIndex = Math.floor(Math.random() * students.length);
        this.randomStudent = students[randomIndex];

        // 显示随机选中的学生
        const randomStudentDisplay = document.getElementById('random-student-display');
        const randomStudentInfo = document.getElementById('random-student-info');

        randomStudentInfo.innerHTML = `
            <div>
                <h2>${this.randomStudent.name}</h2>
                <p>学号: ${this.randomStudent.id}</p>
            </div>
        `;

        randomStudentDisplay.style.display = 'block';
        randomStudentDisplay.classList.add('active');

        // 2秒后移除动画效果
        setTimeout(() => {
            randomStudentDisplay.classList.remove('active');
        }, 2000);
    }

    // 渲染点名列表
    renderAttendanceList() {
        const attendanceListElement = document.getElementById('attendance-list');
        attendanceListElement.innerHTML = '';

        if (this.todayAttendance.length === 0) {
            attendanceListElement.innerHTML = '<tr><td colspan="4" class="text-center">今日暂无点名记录</td></tr>';
            return;
        }

        this.todayAttendance.forEach(record => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${record.studentId}</td>
                <td>${record.studentName}</td>
                <td><span class="status-badge ${this.getStatusClass(record.status)}">${this.getStatusText(record.status)}</span></td>
                <td>
                    <div class="btn-group btn-group-sm" role="group">
                        <button class="btn btn-outline-success btn-status" data-id="${record.studentId}" data-status="present">出勤</button>
                        <button class="btn btn-outline-warning btn-status" data-id="${record.studentId}" data-status="late">迟到</button>
                        <button class="btn btn-outline-danger btn-status" data-id="${record.studentId}" data-status="absent">旷课</button>
                        <button class="btn btn-outline-info btn-status" data-id="${record.studentId}" data-status="early-leave">早退</button>
                    </div>
                </td>
            `;
            attendanceListElement.appendChild(row);
        });

        // 添加状态按钮的事件监听
        document.querySelectorAll('.btn-status').forEach(button => {
            button.addEventListener('click', (e) => {
                const studentId = e.target.dataset.id;
                const status = e.target.dataset.status;
                this.updateAttendanceStatus(studentId, status);
            });
        });
    }

    // 更新点名状态
    updateAttendanceStatus(studentId, status) {
        if (this.addAttendanceRecord(studentId, status)) {
            this.renderAttendanceList();
            this.showMessage('success', `状态已更新为"${this.getStatusText(status)}"`);
        }
    }

    // 按日期查询点名记录
    queryAttendanceByDate(date) {
        const records = this.attendanceRecords.filter(record => record.date === date);
        this.renderStatisticsList(records, date);
        // 同时更新统计信息
        this.renderAttendanceStatistics();
    }

    // 渲染统计列表
    renderStatisticsList(records, date) {
        const statisticsListElement = document.getElementById('statistics-list');
        statisticsListElement.innerHTML = '';

        if (records.length === 0) {
            statisticsListElement.innerHTML = `<tr><td colspan="4" class="text-center">${date} 没有点名记录</td></tr>`;
            return;
        }

        records.forEach(record => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${record.studentId}</td>
                <td>${record.studentName}</td>
                <td>${record.date}</td>
                <td>
                    <div class="d-flex align-items-center">
                        <span class="status-badge ${this.getStatusClass(record.status)}">${this.getStatusText(record.status)}</span>
                        <div class="dropdown ms-2">
                            <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                                修改
                            </button>
                            <ul class="dropdown-menu">
                                <li><a class="dropdown-item change-status" href="#" data-id="${record.studentId}" data-date="${record.date}" data-status="present">出勤</a></li>
                                <li><a class="dropdown-item change-status" href="#" data-id="${record.studentId}" data-date="${record.date}" data-status="late">迟到</a></li>
                                <li><a class="dropdown-item change-status" href="#" data-id="${record.studentId}" data-date="${record.date}" data-status="early-leave">早退</a></li>
                                <li><a class="dropdown-item change-status" href="#" data-id="${record.studentId}" data-date="${record.date}" data-status="absent">旷课</a></li>
                            </ul>
                        </div>
                    </div>
                </td>
            `;
            statisticsListElement.appendChild(row);
        });

        // 添加修改状态的事件监听
        document.querySelectorAll('.change-status').forEach(item => {
            item.addEventListener('click', (e) => {
                e.preventDefault();
                const studentId = e.target.dataset.id;
                const date = e.target.dataset.date;
                const status = e.target.dataset.status;
                this.updateHistoricalAttendanceStatus(studentId, date, status);
            });
        });
    }

    // 更新历史点名状态
    updateHistoricalAttendanceStatus(studentId, date, status) {
        // 查找对应的记录
        const recordIndex = this.attendanceRecords.findIndex(
            record => record.studentId === studentId && record.date === date
        );

        if (recordIndex !== -1) {
            // 更新状态
            this.attendanceRecords[recordIndex].status = status;
            this.saveAttendanceRecords();

            // 重新渲染当前查询的记录
            this.queryAttendanceByDate(date);

            this.showMessage('success', `学生 ${this.attendanceRecords[recordIndex].studentName} 的状态已更新为"${this.getStatusText(status)}"`);
        }
    }

    // 计算学生统计信息
    calculateStudentStatistics() {
        const students = studentManager.getAllStudents();
        const statistics = [];

        students.forEach(student => {
            // 获取该学生的所有记录
            const studentRecords = this.attendanceRecords.filter(record => record.studentId === student.id);

            // 计算各种状态的次数
            const presentCount = studentRecords.filter(record => record.status === 'present').length;
            const lateCount = studentRecords.filter(record => record.status === 'late').length;
            const earlyLeaveCount = studentRecords.filter(record => record.status === 'early-leave').length;
            const absentCount = studentRecords.filter(record => record.status === 'absent').length;

            // 计算总记录数
            const totalCount = studentRecords.length;

            // 计算出勤率 (出勤 + 迟到 + 早退) / 总记录数
            const attendanceRate = totalCount > 0
                ? ((presentCount + lateCount + earlyLeaveCount) / totalCount * 100).toFixed(2) + '%'
                : '0.00%';

            statistics.push({
                id: student.id,
                name: student.name,
                presentCount,
                lateCount,
                earlyLeaveCount,
                absentCount,
                totalCount,
                attendanceRate
            });
        });

        return statistics;
    }

    // 渲染考勤统计信息
    renderAttendanceStatistics() {
        const statistics = this.calculateStudentStatistics();
        const statisticsElement = document.getElementById('attendance-statistics');
        statisticsElement.innerHTML = '';

        if (statistics.length === 0) {
            statisticsElement.innerHTML = '<tr><td colspan="7" class="text-center">暂无学生信息</td></tr>';
            return;
        }

        statistics.forEach(stat => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${stat.id}</td>
                <td>${stat.name}</td>
                <td>${stat.presentCount}</td>
                <td>${stat.lateCount}</td>
                <td>${stat.earlyLeaveCount}</td>
                <td>${stat.absentCount}</td>
                <td>${stat.attendanceRate}</td>
            `;
            statisticsElement.appendChild(row);
        });
    }

    // 显示消息
    showMessage(type, message) {
        // 创建一个toast消息
        const toastId = 'toast-' + Date.now();
        const toastHTML = `
            <div id="${toastId}" class="toast align-items-center text-white bg-${type === 'success' ? 'success' : 'danger'}" role="alert" aria-live="assertive" aria-atomic="true">
                <div class="d-flex">
                    <div class="toast-body">
                        ${message}
                    </div>
                    <button type="button" class="btn-close me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
            </div>
        `;

        // 检查是否已存在toast容器，如果没有则创建
        let toastContainer = document.querySelector('.toast-container');
        if (!toastContainer) {
            toastContainer = document.createElement('div');
            toastContainer.className = 'toast-container position-fixed bottom-0 end-0 p-3';
            document.body.appendChild(toastContainer);
        }

        // 添加toast到容器
        toastContainer.innerHTML += toastHTML;

        // 显示toast
        const toastElement = document.getElementById(toastId);
        const toast = new bootstrap.Toast(toastElement, { delay: 3000 });
        toast.show();

        // 自动移除toast
        toastElement.addEventListener('hidden.bs.toast', () => {
            toastElement.remove();
        });
    }

    // 初始化事件监听
    initEventListeners() {
        // 全部点名按钮
        document.getElementById('btn-attendance-all').addEventListener('click', () => {
            this.attendAll();
        });

        // 随机点名按钮
        document.getElementById('btn-attendance-random').addEventListener('click', () => {
            this.randomAttendance();
        });

        // 随机点名状态按钮
        document.getElementById('btn-present').addEventListener('click', () => {
            if (this.randomStudent) {
                this.updateAttendanceStatus(this.randomStudent.id, 'present');
                document.getElementById('random-student-display').style.display = 'none';
            }
        });

        document.getElementById('btn-late').addEventListener('click', () => {
            if (this.randomStudent) {
                this.updateAttendanceStatus(this.randomStudent.id, 'late');
                document.getElementById('random-student-display').style.display = 'none';
            }
        });

        document.getElementById('btn-absent').addEventListener('click', () => {
            if (this.randomStudent) {
                this.updateAttendanceStatus(this.randomStudent.id, 'absent');
                document.getElementById('random-student-display').style.display = 'none';
            }
        });

        document.getElementById('btn-early-leave').addEventListener('click', () => {
            if (this.randomStudent) {
                this.updateAttendanceStatus(this.randomStudent.id, 'early-leave');
                document.getElementById('random-student-display').style.display = 'none';
            }
        });

        // 查询按钮
        document.getElementById('btn-search-attendance').addEventListener('click', () => {
            const date = document.getElementById('search-date').value;
            if (date) {
                this.queryAttendanceByDate(date);
            } else {
                alert('请选择日期');
            }
        });

        // 设置今天日期为默认值
        document.getElementById('search-date').value = this.currentDate;

        // 初始化时加载统计信息
        this.renderAttendanceStatistics();
    }
}

// 创建点名管理实例
const attendanceManager = new AttendanceManager();